package main

import (
	"flag"
	"fmt"

	"gitee.com/thubcc/blockchain/accounts"
	"gitee.com/thubcc/blockchain/constant"
	name "gitee.com/thubcc/blockchain/nameservice"
	"gitee.com/thubcc/blockchain/p2p"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/log"
)

// cmd arguments
var (
	argVerbosity = flag.Int("verbosity", int(log.LvlError), "log verbosity level")
	argTopic     = flag.String("topic", "44c7429f", "topic in hexadecimal format (e.g. 70a4beef)")
	argPass      = flag.String("password", "123456", "message's encryption password")
	argDataDir   = flag.String("dir", ".ethereum/chain", "ethereum data dir")
	argKeyPass   = flag.String("p", "931", "message's encryption password")
	argPrefix    = flag.String("u", "931", "message's encryption password")
	argMax       = flag.Int64("m", 1000000, "Max search")
	argAddr      = flag.String("addr", "0x69B47aD51691905D4ae1B3b61B27164C1776D08B", "contract address")
	argAbi       = flag.String("abi", "contract/name.abi", "contract abi")
	argUrl       = flag.String("url", "http://localhost:8545", "ethereum rpc")
)

var (
	enodeString = flag.String("n", constant.DefaultNode, "enode")
)

func main() {
	flag.Parse()
	logHandler, err := log.NetHandler("udp", "localhost:9000", log.JSONFormat())
	if err != nil {
		fmt.Println(err)
	}
	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*argVerbosity), logHandler))
	keyConfig := accounts.NewConfig(*argDataDir, true, *argMax)
	prk, err := keyConfig.FindKey(*argPrefix, *argKeyPass)
	if err != nil {
		fmt.Println(err)
		return
	}
	var config = &p2p.Config{*enodeString, prk}

	nameConfig := &name.Config{
		*argUrl,
		*argAbi,
		common.HexToAddress("0xbfadc8b8497d4db8abf422abc7814a90e29f6e08"),
		common.HexToAddress(*argAddr),
		931,
	}
	var service p2p.NameServer
	service, err = nameConfig.NewNameService()
	if err != nil {
		fmt.Println("Initial service failure:", err)
		service = p2p.NilName("raw")
	}
	m, err := p2p.NewP2PMessager(config, service)
	if err != nil {
		fmt.Println(err)
	}
	m.Run(*argTopic, *argPass)
}
